package org.example.string;

public class Invert_String_II {
    public static void main(String[] args) {
        //反转字符串 II

        //给定一个字符串 s 和一个整数 k，从字符串开头算起，每计数至 2k 个字符，就反转这 2k 字符中的前 k 个字符。
        //如果剩余字符少于 k 个，则将剩余字符全部反转。
        //如果剩余字符小于 2k 但大于或等于 k 个，则反转前 k 个字符，其余字符保持原样
        String s = "abcd";
        int k =4;
        char[] chars = s.toCharArray();
        int slow = 0;
        int len = chars.length;
        while(len>0){
            if (len >= 2*k){
                for (int i = 0,j=slow; i < k/2; i++,j++) {
                    char temp = chars[j];
                    chars[j] = chars[slow+k-i-1];
                    chars[slow+k-i-1] = temp;
                }
                len -= 2*k;
                slow = slow + 2*k;
            }else if (len >= k){
                for (int i = 0,j=slow; i < k/2; i++,j++) {
                    char temp = chars[j];
                    chars[j] = chars[slow+k-i-1];
                    chars[slow+k-i-1] = temp;
                }
                break;
            }else {
                for (int i = 0,j=slow; i < len/2; i++,j++) {
                    char temp = chars[j];
                    chars[j] = chars[chars.length-1-i];
                    chars[chars.length-1-i] = temp;
                }
                break;
            }

        }
        String s1 = new String(chars);
        System.out.println(s1);

    }
}
